<?php
class helper_url extends system_view_helper_abstract {
	
	protected $_index = null;
	protected $_params = array();
	protected $_query = array();
	protected $_lang = null;
	public function url($index, $params = array(), $query = array()) {
		$this->_index = $index;
		$this->_params = $params;
		$this->_query = $query;
		return $this;
	}
	
	protected $_front = array();
	protected $_config = array();
	/**
	 * @return system_controller_front
	 */
	protected function getFront() {
		if($this->_lang === null) {
			return system_controller_front::getInstance();
		} else {
			if(!isset($this->_config[$this->_lang])) {
				$this->_config[$this->_lang] = new system_setting_language($this->_lang);
			}
			if(!isset($this->_front[$this->_lang])) {
				$config = $this->_config[$this->_lang]->getConfig();
				$front = new system_controller_front();
				if(isset($config['front']['base_controller'])) {
					$front->setControllerDirectory($config['front']['base_controller']);
				}
				if(isset($config['route'])) {
					$front->startRouter(_DIRECTORY_APP . DIRECTORY_SEPARATOR . $config['route']);
				}
				$this->_front[$this->_lang] = $front;
			}
			return $this->_front[$this->_lang];
		}
	}
	
	protected function getRoute($index) {
		return $this->getFront()->getRouter()->getRoute($index);
	}
	
	protected function isCurrentRoute() {
		return $this->_index == $this->getFront()->getRouter()->getCurrentRouteIndex();
	}
	
	public function assemble($lang = null) {
		$this->_lang = $lang;
		$route = $this->getRoute($this->_index);
		try {
			$url = (string) $route->assemble($this->_params);
		} catch (Exception $e) {
			$url = '';
		}
		if($this->_lang !== null && $url && isset($this->_config[$this->_lang])) {
			$config = $this->_config[$this->_lang];
			$currentBaseUrl = system_controller_front::getInstance()->getBaseUrl();
			$url = $config->getHttp() . preg_replace('#^' . $currentBaseUrl . '(.*)#', '$1', $url);
		}
		return $url . (!empty($this->_query) ? '?' . http_build_query($this->_query) : '');
	}
	
	public function __toString() {
		return $this->assemble();
	}
}
